/*
 * @Description:
 * @Author: fhw
 * @Date: 2022-08-05 11:32:48
 */
/*
 * @Description:
 * @Author: fhw
 * @Date: 2022-08-05 11:32:48
 */
import { forwardRef, Inject, Injectable, UseFilters } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { clone, equals } from 'ramda'
import { UserChatRecord } from 'src/chat-record/entities/user-chat-record.entity'
import { ChatUserService } from 'src/chat_user/chat_user.service'
import { SocketType, socketError, socketSuccess } from 'src/utlis'
import { In, Repository } from 'typeorm'
// import { ChatUserService } from '../chat_user/chat_user.service'
import { HttpExceptionFilter } from '../../http-exception.filter'
import { SendChatDto, SetIsReadDto } from './dto/socket-friend-chat.dto'

@Injectable()
export class SocketFriendChatService {
  constructor(
    @InjectRepository(UserChatRecord)
    private userChatRecordRepository: Repository<UserChatRecord>,
    @Inject(forwardRef(() => ChatUserService)) private readonly chatUserService: ChatUserService,
  ) { }
  @UseFilters(new HttpExceptionFilter())
  async sendChat(params: SendChatDto): Promise<UserChatRecord | SocketType> {
    try {
      if (equals(typeof params, 'string')) {
        params = JSON.parse(params as any)
      }
      const { userId, to_userId, content, type } = params
      const user = await this.chatUserService.getUserInfo({ id: userId })
      const to_user = await this.chatUserService.getUserInfo({ id: to_userId })
      const userChatRecord: UserChatRecord = new UserChatRecord()
      userChatRecord.userId = userId
      userChatRecord.user = user
      userChatRecord.to_userId = to_userId
      userChatRecord.to_user = to_user
      userChatRecord.content = content
      userChatRecord.type = type
      const result = await this.userChatRecordRepository.manager.save(userChatRecord)
      return result
    } catch (error) {
      return socketError(error.message) as SocketType
    }
  }
  async setUserChatRead(ids: number[]): Promise<SocketType> {
    try {
      const { affected } = await this.userChatRecordRepository
        .createQueryBuilder()
        .update(UserChatRecord)
        .set({
          isRead: 1,
        })
        .where({ id: In(ids) })
        .execute()
      if (affected) {
        return socketSuccess('更新成功')
      }
      return socketError('更新失败')
    } catch (error) {
      return socketError(error.message)
    }
  }
  async getChatUnreadRecord(userId: String) {
    try {
      const chatUnreadRecord = await this.userChatRecordRepository.find({
        where: {
          to_userId: Number(userId),
          isRead: 0
        },
      })
      const data = {}
      chatUnreadRecord.forEach(item => {
        if (!data[item?.userId] && equals(item?.user?.del, 1)) {
          data[item.userId] = {
            count: 0, latestNews: null
          };
        }
        data[item?.userId].count++;
        data[item?.userId].latestNews = clone(item);
      })
      return data
    } catch (error) {
      return socketError(error.message) as SocketType
    }
  }
}
